// 图表管理类
class ChartManager {
    constructor() {
        this.charts = {};
        this.loadingIndicator = document.getElementById('loadingIndicator');
        this.init();
    }

    // 初始化所有图表
    async init() {
        this.showLoading();
        try {
            await Promise.all([
                this.initScoreDistributionChart(),
                this.initClassRadarChart(),
                this.initGradeTrendChart(),
                this.initStudentRankingTable(),
                this.initCourseScatterChart(),
                this.initClassPieChart()
            ]);
        } catch (error) {
            console.error('图表初始化失败:', error);
            this.showError('图表加载失败，请刷新页面重试');
        } finally {
            this.hideLoading();
        }
    }

    // 显示加载指示器
    showLoading() {
        this.loadingIndicator.classList.add('show');
    }

    // 隐藏加载指示器
    hideLoading() {
        this.loadingIndicator.classList.remove('show');
    }

    // 显示错误信息
    showError(message) {
        console.error(message);
        // 这里可以集成showState.js来显示错误信息
    }

    // 通用API请求方法
    async fetchData(url) {
        try {
            const response = await fetch(url);
            const result = await response.json();
            if (result.success) {
                return result.data;
            } else {
                throw new Error(result.error || '数据获取失败');
            }
        } catch (error) {
            console.error('API请求失败:', error);
            throw error;
        }
    }

    // 1. 成绩分布柱状图
    async initScoreDistributionChart() {
        const container = document.getElementById('scoreDistributionChart');
        if (!container) return;

        const chart = echarts.init(container);
        this.charts.scoreDistribution = chart;

        try {
            const data = await this.fetchData('/api/charts/score-distribution');
            
            const option = {
                title: {
                    text: '各科目成绩分布',
                    left: 'center',
                    textStyle: { fontSize: 16 }
                },
                tooltip: {
                    trigger: 'axis',
                    axisPointer: { type: 'shadow' }
                },
                legend: {
                    data: data.series.map(s => s.name),
                    bottom: 10
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.courses,
                    axisLabel: {
                        rotate: 45,
                        interval: 0
                    }
                },
                yAxis: {
                    type: 'value',
                    name: '学生人数'
                },
                series: data.series.map(s => ({
                    name: s.name,
                    type: 'bar',
                    stack: 'total',
                    data: s.data,
                    emphasis: { focus: 'series' }
                }))
            };

            chart.setOption(option);
        } catch (error) {
            console.error('成绩分布图表加载失败:', error);
        }
    }

    // 2. 班级雷达图
    async initClassRadarChart() {
        const container = document.getElementById('classRadarChart');
        if (!container) return;

        const chart = echarts.init(container);
        this.charts.classRadar = chart;

        try {
            const data = await this.fetchData('/api/charts/class-radar');
            
            const option = {
                title: {
                    text: '班级平均分对比',
                    left: 'center',
                    textStyle: { fontSize: 16 }
                },
                tooltip: {
                    trigger: 'item'
                },
                legend: {
                    data: data.series.map(s => s.name),
                    bottom: 10,
                    type: 'scroll'
                },
                radar: {
                    indicator: data.indicator,
                    center: ['50%', '55%'],
                    radius: '60%'
                },
                series: [{
                    type: 'radar',
                    data: data.series.map(s => ({
                        value: s.value,
                        name: s.name
                    }))
                }]
            };

            chart.setOption(option);
        } catch (error) {
            console.error('班级雷达图加载失败:', error);
        }
    }

    // 3. 年级趋势折线图
    async initGradeTrendChart() {
        const container = document.getElementById('gradeTrendChart');
        if (!container) return;

        const chart = echarts.init(container);
        this.charts.gradeTrend = chart;

        try {
            const data = await this.fetchData('/api/charts/grade-trend');
            
            const option = {
                title: {
                    text: '年级成绩趋势',
                    left: 'center',
                    textStyle: { fontSize: 16 }
                },
                tooltip: {
                    trigger: 'axis'
                },
                legend: {
                    data: data.series.map(s => s.name),
                    bottom: 10,
                    type: 'scroll'
                },
                grid: {
                    left: '3%',
                    right: '4%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'category',
                    data: data.grades,
                    name: '年级'
                },
                yAxis: {
                    type: 'value',
                    name: '平均分',
                    min: 0,
                    max: 100
                },
                series: data.series.map(s => ({
                    name: s.name,
                    type: 'line',
                    data: s.data,
                    smooth: true,
                    emphasis: { focus: 'series' }
                }))
            };

            chart.setOption(option);
        } catch (error) {
            console.error('年级趋势图加载失败:', error);
        }
    }

    // 4. 学生排名表格
    async initStudentRankingTable() {
        const container = document.getElementById('studentRankingTable');
        if (!container) return;

        try {
            const data = await this.fetchData('/api/charts/student-ranking');
            
            const tableHTML = `
                <table class="table table-striped table-hover">
                    <thead>
                        <tr>
                            <th>排名</th>
                            <th>学号</th>
                            <th>姓名</th>
                            <th>班级</th>
                            <th>平均分</th>
                            <th>加权平均分</th>
                            <th>科目数</th>
                        </tr>
                    </thead>
                    <tbody>
                        ${data.map(student => `
                            <tr>
                                <td><span class="badge ${student.rank <= 3 ? 'bg-warning' : 'bg-secondary'}">${student.rank}</span></td>
                                <td>${student.sno}</td>
                                <td>${student.name}</td>
                                <td>${student.class}</td>
                                <td>${student.avg_score}</td>
                                <td><strong>${student.weighted_avg}</strong></td>
                                <td>${student.course_count}</td>
                            </tr>
                        `).join('')}
                    </tbody>
                </table>
            `;

            container.innerHTML = tableHTML;
        } catch (error) {
            console.error('学生排名表格加载失败:', error);
        }
    }

    // 5. 课程散点图
    async initCourseScatterChart() {
        const container = document.getElementById('courseScatterChart');
        if (!container) return;

        const chart = echarts.init(container);
        this.charts.courseScatter = chart;

        try {
            const data = await this.fetchData('/api/charts/course-scatter');
            
            const option = {
                title: {
                    text: '课程学分与平均分关系',
                    left: 'center',
                    textStyle: { fontSize: 16 }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        const item = data[params.dataIndex];
                        return `${item.name}<br/>学分: ${item.credits}<br/>平均分: ${item.avg_score}<br/>学生数: ${item.student_count}`;
                    }
                },
                grid: {
                    left: '10%',
                    right: '10%',
                    bottom: '15%',
                    containLabel: true
                },
                xAxis: {
                    type: 'value',
                    name: '学分',
                    min: 0,
                    max: 4
                },
                yAxis: {
                    type: 'value',
                    name: '平均分',
                    min: 60,
                    max: 100
                },
                series: [{
                    type: 'scatter',
                    data: data.map(item => ({
                        value: [item.credits, item.avg_score],
                        name: item.name,
                        symbolSize: Math.max(item.student_count / 2, 10)
                    })),
                    emphasis: {
                        focus: 'self'
                    }
                }]
            };

            chart.setOption(option);
        } catch (error) {
            console.error('课程散点图加载失败:', error);
        }
    }

    // 6. 班级饼图
    async initClassPieChart() {
        const container = document.getElementById('classPieChart');
        if (!container) return;

        const chart = echarts.init(container);
        this.charts.classPie = chart;

        try {
            const data = await this.fetchData('/api/charts/class-pie');
            
            const option = {
                title: {
                    text: '班级人数分布',
                    left: 'center',
                    textStyle: { fontSize: 16 }
                },
                tooltip: {
                    trigger: 'item',
                    formatter: function(params) {
                        const item = data[params.dataIndex];
                        return `${params.name}<br/>学生人数: ${params.value}<br/>优秀学生: ${item.excellent_count}<br/>优秀率: ${item.excellent_rate}%`;
                    }
                },
                legend: {
                    bottom: 10,
                    type: 'scroll'
                },
                series: [{
                    type: 'pie',
                    radius: ['30%', '70%'],
                    center: ['50%', '55%'],
                    data: data.map(item => ({
                        value: item.value,
                        name: item.name
                    })),
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }]
            };

            chart.setOption(option);
        } catch (error) {
            console.error('班级饼图加载失败:', error);
        }
    }

    // 响应式处理
    handleResize() {
        Object.values(this.charts).forEach(chart => {
            if (chart && typeof chart.resize === 'function') {
                chart.resize();
            }
        });
    }
}

// 页面加载完成后初始化图表
document.addEventListener('DOMContentLoaded', function() {
    const chartManager = new ChartManager();
    
    // 监听窗口大小变化
    window.addEventListener('resize', () => {
        chartManager.handleResize();
    });
});
